package com.mypage.view.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cloudcc.cloudframe.bus.BullKaoQInEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.AttendancePresenter;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.ImageUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.util.photo.Util;
import com.cloudcc.mobile.weight.DialogUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.bean.NCheckIdBean;
import com.mypage.utils.UtilsShowDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GongniuPhotoActivity extends Activity implements IEventLife {

    @Bind(R.id.mBtnBack)
    Button mBtnBack;
    @Bind(R.id.btnSubmit)
    TextView btnSubmit;
    @Bind(R.id.tvType)
    TextView tvType;
    @Bind(R.id.tvTime)
    TextView tvTime;
    @Bind(R.id.tvAddress)
    TextView tvAddress;
    @Bind(R.id.imgPhoto)
    ImageView imgPhoto;

    private ImageLoadingListener animateFirstListener = new Util.AnimateFirstDisplayListener();
    public SharedPreferences settings;
    public SharedPreferences.Editor editor;
    public String mChange;
    //    public String addr;
    public boolean boolSb;
    public boolean boolZw;
    public boolean boolXb;
    public String mDingwei;
    private DynamicControl upimage = new DynamicControl();
    private List<AddImageInfo> imageArray = new ArrayList<AddImageInfo>();
    private UtilsShowDialog showDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gongniu_photo);
        ButterKnife.bind(this);
        register();
        init();

    }

    public void init() {
        showDialog = new UtilsShowDialog(this);
        settings = this.getSharedPreferences("mIds", 0);
        editor = settings.edit();
        addr = getIntent().getStringExtra("addr");
        tvAddress.setText(addr);
        mDingwei = getIntent().getStringExtra("mDingwei");
        tvType.setText(mDingwei);
        mChange = getIntent().getStringExtra("mChange");
        boolSb = getIntent().getBooleanExtra("boolSb", false);
        boolZw = getIntent().getBooleanExtra("boolSb", false);
        boolXb = getIntent().getBooleanExtra("boolSb", false);
        tvTime.setText(getDateTime());
    }

    @OnClick({R.id.btnSubmit, R.id.imgPhoto, R.id.mBtnBack})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mBtnBack:
                finish();
                break;
            case R.id.btnSubmit:
                // TODO: 2017/11/7 0007 接口方法
//                startLocal(true);
                if (isSelectors) {
                    showDialog.onShowLoadingDialog("正在提交数据...");
                    upimage.sendPhotoKaoqin(imageArray);
                } else {
                    Toast.makeText(this, "照片不能为空，请您拍照", Toast.LENGTH_SHORT).show();
                    return;
                }

                break;
            case R.id.imgPhoto:
                // TODO: 2017/11/7 0007 调用相机

                break;
        }
    }

    public void sendLoca() {
        if (isSelectors) {
//            showDialog.onShowLoadingDialog("正在提交数据...");
            upimage.sendPhotoKaoqin(imageArray);
        } else {
            Toast.makeText(this, "照片不能为空，请您拍照", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public boolean isCreame = true;

    @Override
    protected void onResume() {
        if (isCreame) {
            isCreame = false;
            takePhoto(TAKE_PHOTO_1);

        }
        super.onResume();
    }

    public String InsertString(String src, String dec, int position) {
        StringBuffer stringBuffer = new StringBuffer(src);
        return stringBuffer.insert(position, dec).toString();
    }

    public void sendDataHttp() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        if (boolSb && boolZw && boolXb) {
            params.addBodyParameter("serviceName", "insert");//普通插入服务

        } else {
            params.addBodyParameter("serviceName", "update");//普通更新服务
        }
        params.addBodyParameter("objectApiName", "kqxx");


        if ("上班".equals(mDingwei)) {
            mChange = InsertString(mChange, sbImageString, 2);
        } else if ("中午".equals(mDingwei)) {
            mChange = InsertString(mChange, zwImageString, 2);
        } else if ("下班".equals(mDingwei)) {
            mChange = InsertString(mChange, xbImageString, 2);
        }

        params.addBodyParameter("data", mChange);

//        if (boolSb && boolZw && boolXb) {
////            Log.d("request上班数据接口url---", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=insert&objectApiName=kqxx&data=" + mChange);
//        } else {
//
////            Log.d("request上班数据接口url---", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding() + "&serviceName=update&objectApiName=kqxx&data=" + mChange);
//
//        }

        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        showDialog.onDismissLoadingDialog();

                        Log.d("request上班上传数据接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {

//                        getDataSend();//这个方法在当前考勤页面的onResume里面调用
                        Log.d("request上班上传数据接口成功-------------------------", arg0.result);
                        if (boolSb && boolZw && boolXb) {
                            NCheckIdBean dataId = new Gson().fromJson(arg0.result, NCheckIdBean.class);
                            if (dataId.data.ids.isEmpty()||dataId.data.ids.size()==0) {
                                return;
                            }
                            NCheckIdBean.DataId.CheckId ss = dataId.data.ids.get(0);//有可能数组越界，
                            String id = ss.id;
                            editor.putString("ID", id);
                            editor.commit();
                        }
                        showDialog.onDismissLoadingDialog();
                        finish();
                    }
                });
    }


    public String imagename;
    private static final int TAKE_PHOTO_1 = 5001;

    public void takePhoto(int photo) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File(Environment.getExternalStorageDirectory() + "/"
                    + "CloudCC/photo/");
            if (!dir.exists())
                dir.mkdirs();
            imagename = Tools.getTimeName(System.currentTimeMillis());
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            File f = new File(dir, imagename);// localTempImgDir和localTempImageFileName是自己定义的名字
            Uri u = Uri.fromFile(f);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            startActivityForResult(intent, photo);
        } else {
            Tools.showInfo(this, "请插入SD卡");
        }
    }


    public AddImageInfo imageInfo;
    public String imageUrl;
    public boolean isSelectors = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PHOTO_1) {
            isSelectors = true;
            File f = new File(Environment.getExternalStorageDirectory()
                    + "/" + "CloudCC" + "/photo/" + imagename);
            try {

                Uri u = Uri.parse(MediaStore.Images.Media
                        .insertImage(getContentResolver(),
                                f.getAbsolutePath(), null, null));
                String imageurl = getAbsoluteImagePathx(u);

                imageInfo = new AddImageInfo();
                imageInfo.setImagePath(shuiyin(imageurl));
                imageUrl = shuiyin(imageurl);
                imageArray.add(imageInfo);
//                encode(imageUrl);
                setPhotos();
            } catch (FileNotFoundException e) {
                Tools.handle(e);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public String getAbsoluteImagePathx(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, proj, // Which columns to return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private String shuiyin(String imageurl) {
        // 将图片加上水印
        Bitmap sourBitmap = ImageUtil.getDiskBitmap(imageurl);
        String name = "By"
                + UserManager.getManager().getUser().userName;
        String time = Tools.getTime2(System.currentTimeMillis());

//                String address = currentLoc.getAddress();
        String address = tvAddress.getText().toString();
        // Bitmap fugai =
        // BitmapFactory.decodeResource(getResources(), R.id.a);
        String address1 = null;
        String address2 = null;
        Bitmap textBitmap = ImageUtil.drawTextToLeftBottom(this,
                sourBitmap, name, 100, Color.WHITE, 20, 130);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, time, 100, Color.WHITE, 20, 100);
        textBitmap = ImageUtil.drawTextToLeftBottom(this,
                textBitmap, "", 40, Color.WHITE, 20, 85);
        if (address.length() > 20) {
            address1 = address.substring(0, 20);
            address2 = address.substring(11, address.length());
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address1, 100, Color.WHITE, 20, 70);
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address2, 100, Color.WHITE, 20, 40);

        } else {
            textBitmap = ImageUtil.drawTextToLeftBottom(this,
                    textBitmap, address, 100, Color.WHITE, 20, 30);
        }

        // 存储图片
        savePhotoToSDCard(Environment.getExternalStorageDirectory()
                        + "/" + "CloudCC" + "/photo", imagename + ".jpg",
                textBitmap);

        imageurl = Environment.getExternalStorageDirectory() + "/"
                + "CloudCC" + "/photo/" + imagename + ".jpg";

        return imageurl;
    }

    /**
     * 设置选中的 图片
     */

    private void setPhotos() {
        List<String> selectedImagePathArray = AppContext.selectPhotos;

        for (String imagePath : selectedImagePathArray) {
            if (imageArray.contains(imagePath)) {// 去重
                continue;
            }
            AddImageInfo imageInfo = new AddImageInfo();

            imageInfo.setImagePath(imagePath);
            imageArray.add(imageInfo);
        }
        AddImageInfo localImageInfo = imageArray.get(0);
//        adapter = new AddmicroPostGridviewAdapter(mContext, imageArray);
//        containerGridViewPhoto.setAdapter(adapter);
//        setAdapterListener();
        selectedImagePathArray.clear();
        ImageLoader.getInstance().displayImage("file://" + localImageInfo.getImagePath(), imgPhoto,
                Constants.IM_IMAGE_OPTIONS, animateFirstListener);
//        encode("file://" + imageInfo.getImagePath());
        selectedImagePathArray.clear();
    }

    public void savePhotoToSDCard(String path, String photoname, Bitmap pBitmap) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();
                File photoFile = new File(path, photoname);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(photoFile);
                    if (pBitmap != null) {
                        if (pBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                                fileOutputStream)) {
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    try {
                        fileOutputStream.close();
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
            }
        }
    }

    ////--------------------------------------------------up


    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }
//------------------------

    @Override
    protected void onDestroy() {
        LocationManager.getInstance().unregisterlistener(mListener);
        super.onDestroy();
        unRegister();
    }

    //    String encodeString;
    String sbImageString;
    String zwImageString;
    String xbImageString;

    public void onEventMainThread(BullKaoQInEvent event) {


        String id = event.imgurl;//图片的ID
        sbImageString = "\"sbzp\":\"" + id + "\",";
        zwImageString = "\"zwzp\":\"" + id + "\",";
        xbImageString = "\"xbzp\":\"" + id + "\",";
        sendDataHttp();


    }

    public String getDateTimes() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return sdf.format(d);
    }

//    --------------------------
    /**
     * 开始定位
     *
     * @param isShowWaiting 是否显示 定位进行的时候的dialog 提示
     */
    private AttendancePresenter mAttendancePresenter = new AttendancePresenter();

    private AttendancePresenter.AttendanceHomeEntity mHomeEntity;
    private String mEns = RunTimeManager.getInstance().getlanguage();
    private boolean shouldShowWaiting = false;// 是否显示dialog 在定位的时候

    private void startLocal(boolean isShowWaiting) {
        shouldShowWaiting = isShowWaiting;
        if (isShowWaiting) {// 显示定位的等待提示
            if ("en".equals(mEns)) {
                showDialogTy("Is positioning, please wait...");
            } else {
                showDialogTy("正在定位,请稍等...");
            }

        }
        LocationManager.getInstance().registerListener(mListener);
        LocationManager.getInstance().requestLocal();
    }


    public String getDateTime() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return sdf.format(d);
    }

    public String getDatea() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(d);
//        return "('" + sdf.format(d) + "','yyyy-MM-dd')";
    }


    public void setNoonData() {
        String mChange = "";
        JSONObject object = new JSONObject();

        try {
            object.put("zwbgsj", getDateTime());
            object.put("zwqdzb", String.valueOf(lastDBLocation.getLongitude()) + "," + String.valueOf(lastDBLocation.getLatitude()));
            object.put("zwqddz", addr);
            object.put("kqrq", getDatea());
            if (boolSb && boolZw && boolXb) {

            } else {
                object.put("id", settings.getString("ID", " "));
            }
            mChange = "[" + object.toString() + "]";
            System.out.println(mChange);

        } catch (JSONException e) {

            e.printStackTrace();
        }
        sendLoca();
    }

    public void setJsonString() {
        String mChange = "";
        JSONObject object = new JSONObject();

        try {
            object.put("bgsj", getDateTime());
            object.put("qdzb", String.valueOf(lastDBLocation.getLongitude()) + "," + String.valueOf(lastDBLocation.getLatitude()));
            object.put("qddz", addr);
            object.put("kqrq", getDatea());

            if (boolSb && boolZw && boolXb) {

            } else {
                object.put("id", settings.getString("ID", " "));
            }
            mChange = "[" + object.toString() + "]";
            System.out.println(mChange);

        } catch (JSONException e) {

            e.printStackTrace();
        }
        sendLoca();
    }

    public void setOffWorkData() {
        String mChange = "";
        JSONObject object = new JSONObject();

        try {
            object.put("xbbgsj", getDateTime());
            object.put("xbqtzb", String.valueOf(lastDBLocation.getLongitude()) + "," + String.valueOf(lastDBLocation.getLatitude()));
            object.put("xbqtdz", addr);
            object.put("kqrq", getDatea());
            if (boolSb && boolZw && boolXb) {

            } else {
                object.put("id", settings.getString("ID", " "));
            }
            mChange = "[" + object.toString() + "]";
            System.out.println(mChange);

        } catch (JSONException e) {

            e.printStackTrace();
        }
        sendLoca();
    }


    /**
     * 签到签退
     *
     * @param checkInOrOut 2016-4-27
     */
    String addr = "";

    private void checkToNet(int checkInOrOut) {

        addr = LocationManager.getDetailAddr(lastDBLocation, false);

        //经度  维度 类型 位置 签到
        mAttendancePresenter.check(String.valueOf(lastDBLocation.getLongitude()), String.valueOf(lastDBLocation.getLatitude()), String.valueOf(attendanceTypeIndex), addr, checkInOrOut);
        if (!"定位".equals(mDingwei)) {
//            tureDialog.show();
//            tureDialog.setTextTitleAndBt(addr, getString(R.string.qiandao));
            if ("上班".equals(mDingwei)) {
                setJsonString();
            } else if ("中午".equals(mDingwei)) {
                setNoonData();
            } else if ("下班".equals(mDingwei)) {
                setOffWorkData();
            }
            isCreame = false;
        }


    }

    private BDLocation lastDBLocation;// 最新的定位位置
    private BDLocationListener mListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                lastDBLocation = location;
                LocationManager.getInstance().stopRequestLocal();
                LocationManager.log(lastDBLocation);
                onLocalFinish(true);
            } else {
                if (null != location) {
                    if ("en".equals(mEns)) {
                        showToast("Positioning failed, please try again! Error code:" + location.getLocType());
                    } else {
                        showToast("定位失败，请重试! 错误码:" + location.getLocType());
                    }

                }
                onLocalFinish(false);
            }
        }
    };

    /**
     * show toast
     *
     * @param msg
     */
    protected void showToast(String msg) {
        if (null != msg && !TextUtils.isEmpty(msg)) {
            Toast.makeText(this, msg, 0).show();
        }
    }

    /**
     * 定位结束的时候
     *
     * @param success 是否定位成功
     */
    private void onLocalFinish(boolean success) {
        if (shouldShowWaiting) {// 刚才显示dialog 了 取消吊
            dismissWainting();
        }
        if (!success) {
            if ("en".equals(mEns)) {
                showToast("Location failed, please try again");
            } else {
                showToast("定位失败,请重试");
            }


            return;
        }
        checkToNet(1);//在这个类中随意数字

    }

    /**
     * 取消 显示等待的dialog
     */
    protected void dismissWainting() {
        if (callLogLoadingDialogx != null) {
            callLogLoadingDialogx.dismiss();
            callLogLoadingDialogx = null;
        }
        showLocResult();
    }

    private void showLocResult() {
        showLocalResult(new DialogUtils.DialogOnClickListener() {
            @Override
            public void onClickPositive(Dialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onClickNegative(Dialog dialog) {
                dialog.cancel();
            }
        });
    }

    CallLogLoadingDialog callLogLoadingDialogx;

    protected void showDialogTy(String text) {
        callLogLoadingDialogx = new CallLogLoadingDialog(GongniuPhotoActivity.this, R.style.DialogLoadingTheme);
        callLogLoadingDialogx.show();
        callLogLoadingDialogx.settext(text);
    }

    /**
     * 显示点击显示的结果 2016-4-22
     */
    private void showCheckInResult() {
        showLocalResult(new DialogUtils.DialogOnClickListener() {
            @Override
            public void onClickPositive(Dialog dialog) {
                dialog.cancel();
//                check(1);

            }

            @Override
            public void onClickNegative(Dialog dialog) {
                dialog.cancel();
            }
        });
    }

    /**
     * 显示 当前位置dialog
     */
    private int attendanceTypeIndex = 1;// 默认是 内勤

    private void showLocalResult(DialogUtils.DialogOnClickListener l) {
        String addr = LocationManager.getDetailAddr(lastDBLocation, true);

        // 计算 距离
        String distanceStr = "";
        if (null != lastDBLocation
                && hasCheckCenter()
                && (!(attendanceTypeIndex == 2 && mHomeEntity.checkloc.type == 1))) {// 存在坐标点
            // 的时候才显示
            // 距离
            LatLng lastLatLng = new LatLng(lastDBLocation.getLatitude(),
                    lastDBLocation.getLongitude());
            LatLng latLng = new LatLng(mHomeEntity.checkloc.lat,
                    mHomeEntity.checkloc.lon);
            double distance = DistanceUtil.getDistance(lastLatLng, latLng);
            distanceStr = "距离签到点:" + String.valueOf((int) distance) + "m";
        }

        if (TextUtils.isEmpty(addr)) {
            return;
        }
        String message = addr + "\n" + distanceStr;
        if ("定位".equals(mDingwei)) {
            if ("en".equals(mEns)) {
                DialogUtils.showWarnGongniu(this, "prompt", "position" + message, l);
            } else {
                DialogUtils.showWarnGongniu(this, "提示", "位置：" + message, l);
            }
        }
    }

    /**
     * 服务器是否配置了签到中心点
     *
     * @return 2016-3-30
     */
    private boolean hasCheckCenter() {
        return null != mHomeEntity && null != mHomeEntity.checkloc
                && mHomeEntity.checkloc.lat > 0 && mHomeEntity.checkloc.lon > 0;
    }


//    -------------------------

}